package com.klm.netty.codec;

import com.google.protobuf.Message;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 消息类型注册表
 */
@Slf4j
@Component
public class MessageTypeRegistry {
    private final Map<Integer, Message> messageTypes = new ConcurrentHashMap<>();
    private int nextTypeId = 1;

    /**
     * 注册消息类型
     * @param message 消息实例
     * @return 消息类型ID
     */
    public int registerMessageType(Message message) {
        int typeId = nextTypeId++;
        messageTypes.put(typeId, message);
        log.debug("Registered message type {} for {}", typeId, message.getClass().getSimpleName());
        return typeId;
    }

    /**
     * 获取消息原型
     * @param typeId 消息类型ID
     * @return 消息原型
     */
    public Message getPrototype(int typeId) {
        Message prototype = messageTypes.get(typeId);
        if (prototype == null) {
            throw new IllegalArgumentException("Unknown message type: " + typeId);
        }
        return prototype;
    }

    /**
     * 获取消息类型ID
     * @param message 消息实例
     * @return 消息类型ID
     */
    public int getTypeId(Message message) {
        for (Map.Entry<Integer, Message> entry : messageTypes.entrySet()) {
            if (entry.getValue().getClass().equals(message.getClass())) {
                return entry.getKey();
            }
        }
        return registerMessageType(message);
    }

    /**
     * 获取所有已注册的消息类型
     * @return 消息类型映射
     */
    public Map<Integer, Message> getAllMessageTypes() {
        return new ConcurrentHashMap<>(messageTypes);
    }
} 